//
//  ThingsConduit.m
//  Task Views
//
//  Created by Chris Karr on 2/24/09.
//  Copyright 2009 Chris J. Karr. All rights reserved.
//

#import "ThingsConduit.h"

@implementation ThingsConduit

- (NSArray *) fetchTasks:(NSDictionary *) options
{
	NSMutableArray * tasks = [NSMutableArray array];

	NSArray *paths = NSSearchPathForDirectoriesInDomains(NSApplicationSupportDirectory, NSUserDomainMask, YES);
	NSString *basePath = ([paths count] > 0) ? [paths objectAtIndex:0] : NSTemporaryDirectory();
	NSString * xmlPath = [[[basePath stringByAppendingPathComponent:@"Cultured Code"] stringByAppendingPathComponent:@"Things"] 
						  stringByAppendingPathComponent:@"Database.xml"];
	
	NSError * error = nil;
	
	NSXMLDocument * doc = [[NSXMLDocument alloc] initWithContentsOfURL:[NSURL fileURLWithPath:xmlPath] options:0 error:&error];
	
	if (doc != nil)
	{
		NSXMLElement * database = [doc rootElement];
		
		NSArray * objects = [database elementsForName:@"object"];
		
		NSEnumerator * objectIter = [objects objectEnumerator];
		NSXMLElement * object = nil;
		while (object = [objectIter nextObject])
		{
			NSString * type = [[object attributeForName:@"type"] stringValue];
			
			if ([type isEqual:@"TODO"])
			{
				NSMutableDictionary * task = [NSMutableDictionary dictionary];
				
				NSArray * attributeElements = [object elementsForName:@"attribute"];
				
				NSEnumerator * attIter = [attributeElements objectEnumerator];
				NSXMLElement * attribute = nil;
				while (attribute = [attIter nextObject])
				{
					NSString * name = [[attribute attributeForName:@"name"] stringValue];
					NSString * type = [[attribute attributeForName:@"type"] stringValue];
					NSObject * value = [attribute stringValue];
					
					if ([name isEqual:@"identifier"])
						value = [NSString stringWithFormat:@"Things:%@", [value description]];
					else if ([type isEqual:@"date"])
					{
						NSScanner * scanner = [NSScanner scannerWithString:[value description]];
						
						double valueToGet;
						
						if ([scanner scanDouble:&valueToGet] == YES) 
							value = [NSDate dateWithTimeIntervalSinceReferenceDate:valueToGet];
					}
					else if ([type hasPrefix:@"int"])
					{
						NSScanner * scanner = [NSScanner scannerWithString:[value description]];

						long long valueToGet;

						if ([scanner scanLongLong:&valueToGet] == YES) 
							value = [NSNumber numberWithLongLong:valueToGet];
					}
					
					[task setValue:value forKey:name];
					
					if ([name isEqual:@"title"])
						[task setValue:value forKey:@"name"];
				}
				
				[task setValue:@"Things" forKey:@"source"];
				
				[tasks addObject:task];
			}
		}
	}
	else
	{
		// Do something with error.
	}
	
	
	return tasks;
}

- (void) openExternalSite:(NSDictionary *) options
{
	[[NSWorkspace sharedWorkspace] launchApplication:@"Things"];
}

- (NSString *) identifier
{
	return @"identifier";
}


@end
